package cn.com.agree.common.util;

import cn.com.agree.common.constant.GloPropertyConstant;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.geronimo.mail.util.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashSet;
import java.util.List;


/**
 * RSA加解密
 * @author xrp09
 * created at 2019年6月19日
 */
public class RSAUtil {
    
    /** *//** 
     * RSA最大加密明文大小 
     */  
    private static final int MAX_ENCRYPT_BLOCK = 117;  
      
    /** *//** 
     * RSA最大解密密文大小 
     */  
    private static final int MAX_DECRYPT_BLOCK = 128; 

    public static final String KEY_ALGORITHM = "RSA";
    private static KeyFactory keyFactory = null;
    public static String PrivateKey ="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIlrGUO0BASsEPzt+RsxsfHfHfWcIvzpyzdfrU/fNZepXb012EW2/jWroFRvPPM13sS5RCGudmBIwjvWVSvNpUJi0Ugp37FV1DnMgHQoeiUYoMSpog7GCJhTOxkPR0UU6s14vjmjI+92tRy3kOiP2MgsbBHu1dQ/GsL6sX0njb21AgMBAAECgYAO3lKue6TPqJpx84G3ion5ZK3GLG2wtc8yH50N/lW7Ii0tUs0ixej9f6NqX1rV6ec/m9geWNUgF99EQC2Y/rg5rHmA55et8ns2eWP2Zl0n3mBJqc6fv+srnyvgOcEMlUy3gw15wNCG5HspLtSVA1A5EVMrJHxjum+g0lY6anXRhQJBAN0pmpdmSsmobbx56DXZ02R9tyW3t5G7KK24/GGZqdKq4GjdlQiAiC8a+CCCk4IDcfN/4WGgcpEpeiG3/BmxcYsCQQCfEIE8PcbKOY26hSDSL76RgmWjGORqh92sYsLVaqk3u7DaHzcGEWrIA+8oxcXN/w6cs0afWUJinuPoR7XPgPW/AkBQaDbXQo6AQKcc9ilxoq9Tgs1afi/UYPpKJs5DYc23VP7fwWfUvn5EugZqM28TvtLoF59GkkH0+uJ3bd/PK48/AkEAgHfxGPmAC6ZOPL33Eytyi804T3D0UsInHGqrl3jM8PGLVa/uXd1FVAQxbcnGB6kfYRo+SMbrogFYays3wT8TuwJACNWfc+xQ8ccT7ko3CVxtceEHjIDzi3iE8bXU098E2542/7vWeplWgkv6fRNHuquzV73bVmIHCdpyAWg0aAzX8g==\r\n" + 
    		"";
    public static String publicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJaxlDtAQErBD87fkbMbHx3x31nCL86cs3X61P3zWXqV29NdhFtv41q6BUbzzzNd7EuUQhrnZgSMI71lUrzaVCYtFIKd+xVdQ5zIB0KHolGKDEqaIOxgiYUzsZD0dFFOrNeL45oyPvdrUct5Doj9jILGwR7tXUPxrC+rF9J429tQIDAQAB\r\n" + 
    		"";
    public  static String unitCode = "gdnx";

    public  final static String DateFormat = "yyyyMMdd";


    static {
        try {
            keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 解密方法
     * @param dataStr 要解密的数据
     * @return 解密后的原数据
     * @throws Exception
     */
    public static String decrypt(String dataStr) throws Exception{
        //要加密的数据
        System.out.println("要解密的数据:"+dataStr);
        //对私钥解密
        Key decodePrivateKey = getPrivateKeyFromBase64KeyEncodeStr(PrivateKey);
        //Log.i("机密",""+decodePrivateKey);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, decodePrivateKey);
        byte[] encodedData = Base64.decode(dataStr);
        byte[] decodedData = cipher.doFinal(encodedData);
        String decodedDataStr = new String(decodedData,"utf-8");
        System.out.println("私钥解密后的数据:"+decodedDataStr);
        return decodedDataStr;
    }

    /**
     * 获取base64加密后的字符串的原始私钥
     * @param keyStr
     * @return
     */
    public  static Key getPrivateKeyFromBase64KeyEncodeStr(String keyStr) {
        byte[] keyBytes = Base64.decode(keyStr);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        Key privateKey=null;
        try {
            privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return privateKey;
    }

    /**
     * 获取base64加密后的字符串的原始公钥
     * @param keyStr
     * @return
     */
    public static Key getPublicKeyFromBase64KeyEncodeStr(String keyStr) {
        byte[] keyBytes = Base64.decode(keyStr);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        Key publicKey = null;
        try {
            publicKey = keyFactory.generatePublic(x509KeySpec);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return publicKey;
    }

    /**
     * 公钥加密方法
     * @param dataStr 要加密的数据
     * @param dataStr 公钥base64字符串
     * @return 加密后的base64字符串
     * @throws Exception
     */
    public static String encryptPublicKey(String dataStr) throws Exception{
        //要加密的数据
        System.out.println("要加密的数据:"+dataStr);
        byte[] data = dataStr.getBytes();
        // 对公钥解密
        Key decodePublicKey = getPublicKeyFromBase64KeyEncodeStr(publicKey);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, decodePublicKey);
        byte[] encodedData = cipher.doFinal(data);
        String encodedDataStr = new String(Base64.encode(encodedData));
        System.out.println("公钥加密后的数据:"+encodedDataStr);
        return encodedDataStr;
    }
    
    /**
     * 使用公钥进行分段加密
     * @param dataStr 要加密的数据
     * @return 公钥base64字符串
     * @throws Exception
     */
    public static String encryptByPublicKey(String dataStr)  
            throws Exception {  
        //要加密的数据
        System.out.println("要加密的数据:"+dataStr);
        byte[] data = dataStr.getBytes();
        // 对公钥解密
        Key decodePublicKey = getPublicKeyFromBase64KeyEncodeStr(publicKey);
//        System.out.println("公钥："+new String(Base64.decode(decodePublicKey.getEncoded())));
       
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
        // 对数据加密  
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
        cipher.init(Cipher.ENCRYPT_MODE, decodePublicKey);  
        int inputLen = data.length;  
        ByteArrayOutputStream out = new ByteArrayOutputStream();  
        int offSet = 0;  
        byte[] cache;  
        int i = 0;  
        // 对数据分段加密  
        while (inputLen - offSet > 0) {  
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {  
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);  
            } else {  
                cache = cipher.doFinal(data, offSet, inputLen - offSet);  
            }  
            out.write(cache, 0, cache.length);  
            i++;  
            offSet = i * MAX_ENCRYPT_BLOCK;  
        }  
        byte[] encryptedData = out.toByteArray();  
        out.close(); 
        String encodedDataStr = new String(Base64.encode(encryptedData));
        System.out.println("公钥加密后的数据:"+encodedDataStr);
        System.out.println(encodedDataStr);
        return encodedDataStr;  
    } 

    /**
     * 使用私钥进行分段解密
     * @param dataStr 使用base64处理过的密文
     * @return 解密后的数据
     * @throws Exception
     */
    public static String decryptByPrivateKey(String dataStr,String PrivateKey)  
            throws Exception {  
        
        byte[] encryptedData = Base64.decode(dataStr);
        
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
        Key decodePrivateKey = getPrivateKeyFromBase64KeyEncodeStr(PrivateKey);
//        System.out.println("私钥："+new String(Base64.decode(decodePrivateKey.getEncoded())));
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
        cipher.init(Cipher.DECRYPT_MODE, decodePrivateKey);  
        int inputLen = encryptedData.length;  
        ByteArrayOutputStream out = new ByteArrayOutputStream();  
        int offSet = 0;  
        byte[] cache;  
        int i = 0;  
        // 对数据分段解密  
        while (inputLen - offSet > 0) {  
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {  
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);  
            } else {  
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);  
            }  
            out.write(cache, 0, cache.length);  
            i++;  
            offSet = i * MAX_DECRYPT_BLOCK;  
        }  
        byte[] decryptedData = out.toByteArray();  
        out.close();  
        String decodedDataStr = new String(decryptedData,"utf-8");
        System.out.println("私钥解密后的数据:"+decodedDataStr);
        return decodedDataStr;  
    } 
    
    public  static boolean compareResult(List<String> list,List<String> list1){
		boolean has = false;
		HashSet<String> set = new HashSet<String>(list);
		set.retainAll(list1);
		if(set.size() > 0){
		    has =  true;
		 }
		return has;
	}

    
    public static void genLicenseFile(JSONArray jmacs,String edate,String reslicpath)throws Exception {

//    	String path = System.getProperty("user.dir");
//    	System.out.println(path);
//    	System.out.println("------------------------全部转换----------------------------");
//    	String lic = path+ File.separator+ GloPropertyConstant.LICENSE_FILENAME;
//    	System.out.println("lic路径是："+lic);
//        System.out.println("---------------------");
//        System.out.println(FileUtil.getResourceBasePath());

            String mac=null;
            for (Object object : jmacs) {
                mac = (String)object;
//			    mac=mac.toUpperCase();
                System.out.println(mac);
            }
            JSONObject json = new JSONObject();
            json.put("unitCode", GloPropertyConstant.LICENSE_UNITCODE);
            json.put("endDate",edate);
            json.put("maclist", jmacs);

            //生成lic
            String tdata =  "|"+json.toString()+"|";
            System.out.println("=================================================");
            String test=GloPropertyConstant.LICENSE_FILELICCOMPANY+"|"+json.toString()+"|";
            String encryptByPublicKey = encryptByPublicKey(test);
//          默认key私钥加密   默认key在配置中 unitcode叠加
            String encrypt = DESUtil.encrypt(PrivateKey,"");
            System.out.println("私钥加密:");// 写入文件 ：  加密的私钥   $| 加密的数据(|)
            System.out.println(encrypt);
            System.out.println("-----------------------------------");
            String decrypt = DESUtil.decrypt(encrypt,"");
            System.out.println("获取解密的私钥:"+decrypt);
            //通过私钥解密数据
            decryptByPrivateKey(encryptByPublicKey,decrypt);
            FileUtil.writeFile(encrypt+GloPropertyConstant.LICENSE_SEPARATOR+encryptByPublicKey, reslicpath);

    }
}
